<?php
namespace Home\Controller;
use Think\Controller;
use Think\Verify;
class UserController extends Controller {
	
	public function __construct() {
		parent::__construct();
		if(empty($_SESSION['user']['id']))
		{
			$this->redirect('Home/Login/login');
		}
    }
	
    public function index(){
	    $pageNo=empty($_REQUEST['pageNo'])?1:$_REQUEST['pageNo'];
		$pageSize=empty($_REQUEST['pageSize'])?10:$_REQUEST['pageSize'];
		$username=empty($_REQUEST['username'])?'':$_REQUEST['username'];
		$type=empty($_REQUEST['type'])?'':$_REQUEST['type'];
		$name=empty($_REQUEST['name'])?'id':$_REQUEST['name'];
		$asc=empty($_REQUEST['asc'])?'desc':trim($_REQUEST['asc']);
		
		$res=D('user_list')->user_list($pageNo,$pageSize,$username,$type,$name='id',$asc='desc');
		
		$this->assign('user_list',$res['user_list']);
		$this->assign('count',$res['count']);
		$this->assign('data',$res['data']);
		$this->display();
    }
	
    public function user_info(){
	    $id=empty($_REQUEST['id'])?'':$_REQUEST['id'];
		
		if(!empty($id))
	    {
			 $userinfo=D('user_list')->user_info_id($id);
		}
       
		$this->assign('jumpurl',$_SERVER['HTTP_REFERER']);
		$this->assign('userinfo',$userinfo);
		$this->display();
    }
	
	public function user_edit(){
	    if(IS_POST)
		{
			$id=$_POST['id'];
			$jumpurl=$_POST['jumpurl'];
			$username = trim($_POST['username']);
			
			if(empty($id))
			{
				$row	=	M('user_list') -> field('id') -> where("username='".$username."'") -> find();
				if(!empty($row))
				{
					$this->error('用户已存在');
				}else{
					$data['username']=$username;
					$data['password'] = md5(trim($_POST['password']));
					$data['type']     = $_POST['type'];
					$res	=	M('user_list') -> add($data);
					
					header("Location:index");
				}
			}
			else
			{
				$row	=	M('user_list') -> field('id') -> where("id != ".$id." and username='".$username."'") -> find();
				if(!empty($row))
				{
					$this->error('用户已存在');
				}
				else
				{
					$data['username']=$username;
					$data['type']     = $_POST['type'];
					if(!empty($_POST['password']))
					{
						$data['password'] = md5(trim($_POST['password']));
					}
					
					$res	=	M('user_list') ->where('id='.$id)-> save($data);
					
					header("Location:".$jumpurl);
				}
			}
			
		}
    }
    
	public function user_delete(){
	    $id=empty($_REQUEST['id'])?'':$_REQUEST['id'];
		
		$res=M('user_list')->where('id='.$id)->delete();
		
		header("Location:".$_SERVER['HTTP_REFERER']);
    }
	
}